package com.qfmy.app.service.impl.community;

import com.qfmy.app.mapper.community.PostCommentMapper;
import com.qfmy.app.service.community.PostCommentService;
import com.qfmy.common.exception.BaseException;
import com.qfmy.common.login.LoginUser;
import com.qfmy.common.login.LoginUserHolder;
import com.qfmy.common.result.ResultCodeEnum;
import com.qfmy.model.entity.community.PostComment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 清风明月
 * @Package com.qfmy.app.service.impl.community
 * @date 2025/4/17
 * @description 帖子评论
 */
@Service
@SuppressWarnings("all")
public class PostCommentServiceImpl implements PostCommentService {

      /**
       * 注入mapper
       */
      @Autowired
      private PostCommentMapper postCommentMapper;

      /**
       * 添加帖子评论
       * @param postId
       * @param content
       */
      @Override
      @Transactional(rollbackFor = Exception.class)
      public void addPostComment(Integer postId, String content) {
           //获取用户id
          Integer userId = getUserId();
          //添加评论
          postCommentMapper.addPostComment(postId, userId, content);
      }

      /**
       * 获取帖子评论
       * @return
       */
      @Override
      public List<PostComment> getPostComment(Integer pageNum, Integer size, Integer postId) {
            //计算分页
           int start = getStart(pageNum, size);
           return postCommentMapper.getPostComment(start, size, postId);
      }


    /**
       * 计算分页
       * @param pageNum
       * @param size
       * @return
       */
      private int getStart(Integer pageNum, Integer size) {
            pageNum = Math.max(pageNum, 1);
            size = Math.max(size, 15);
            return (pageNum - 1) * size;
      }

      /**
       * 获取用户id
       * @return
       */
      private Integer getUserId() {
            LoginUser loginUser = LoginUserHolder.getLoginUser();
             if(loginUser == null)
             {
                  throw new BaseException(ResultCodeEnum.TOKEN_INVALID);
             }
             return loginUser.getUserId();
      }
}
